package com.base.common.util.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.commons.lang3.StringUtils;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @title  pdf文档添加 二维码
 * @Author 覃球球
 * @Version 1.0 on 2019/3/5.
 * @Copyright 贝旺科技
 */
public class AddQrcodeToPdfFileUtils {

    /**
     * pdf文档添加二维码
     * @param info
     */
    public static void addQrcodeToPdf(QrcodePdfInfo info){
        String qrcodeUrl = info.getHostUrl();
        if(StringUtils.isNotBlank(info.getCodeText())){
            qrcodeUrl += "/" + info.getCodeText();
        }
        BarcodeQRCode barcodeQRCode = new BarcodeQRCode(qrcodeUrl, 200, 200, null);
        Image codeQrImage = null;
        PdfReader pdfReader = null;
        PdfWriter writer = null;
        Document document = null;
        try {
            codeQrImage = barcodeQRCode.getImage();
            pdfReader = new PdfReader(info.getOriginPdfFileUrl());
            int page = pdfReader.getNumberOfPages();
            Rectangle psize = pdfReader.getPageSize(1);
            //float width = psize.getWidth();
            float height = psize.getHeight();
            // 创建一个文档变量
            document = new Document(psize, 50, 50, 50, 50);//50页面空白边距
            writer = PdfWriter.getInstance(document, new FileOutputStream(info.getDestPdfFileUrl()));
            document.open();
            for(int i = 1; i <= page; i++){
                PdfContentByte cb = writer.getDirectContent();
                PdfImportedPage page11 =writer.getImportedPage(pdfReader, i);
                BaseFont bfbf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                Image imglift = Image.getInstance(codeQrImage);
                cb.addTemplate(page11, 1.0f, 0, 0,1.0f, 0, 0);
//              System.out.println("width : " + width  + " \t " + height);
                cb.addImage(imglift,info.getQrcodeWidth(), 0, 0 , info.getQrcodeHeight()
                        , info.getQrcodeLeft(), height - info.getQrcdoeTop());//所添加图像的比例，位置20140626
                cb.beginText();//添加文字
                cb.setFontAndSize(bfbf, 10);
                cb.endText();
                document.newPage();
            }
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if(document != null){
                document.close();
            }
        }
    }
}
